package br.com.medvagas.web.conversor;

import java.util.Date;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;

import org.apache.commons.lang.StringUtils;

import br.com.medvagas.comum.funcoes.FuncoesDataHora;
import br.com.medvagas.comum.util.JSFMensagem;
import br.com.medvagas.comum.util.UtilJSF;

@FacesConverter("conversorDataHora")
public class ConversorDataHora implements Converter {
	
	@Override
	public String getAsString(FacesContext facesContext, UIComponent uiComponent, Object valor) 
			throws ConverterException {
		
		if (valor != null && valor instanceof Date) {
			return FuncoesDataHora.dataHoraMinToString((Date) valor);
		}
		
		return "";
	}

	@Override
	public Object getAsObject(FacesContext facesContext, UIComponent uiComponent, String novoValor) 
			throws ConverterException {

		Date data = null; 
		
		if (StringUtils.isNotEmpty(novoValor)) {
			
			try {
				
				data = FuncoesDataHora.stringToData(novoValor);
				
			} catch (Exception e) {
				FacesMessage facesMessage = new FacesMessage(
						FacesMessage.SEVERITY_ERROR, 
						JSFMensagem.getMensagemAplicacaoFormatada("MSG_0017", 
								UtilJSF.getLabelComponente(uiComponent.getClientId(facesContext))),
						null);	
				throw new ConverterException(facesMessage);
			}
		}
		
		return data;
	}

}
